import Taro, { useReachBottom, useRouter } from "@tarojs/taro";
import { Text, View } from "@tarojs/components";

import ByRow from "@/components/ui/ByRow";
import Card from "@/components/common/Card";
import ByCell from "@/components/ui/ByCell";
import ByText from "@/components/ui/ByText";
import Page from "@/components/common/Page";
import FooterNav from "./components/FooterNav";

import useList from "@/hooks/useList";
import ApiMokan from "@/api/mokan";
import ListView from "@/components/app/ListView";
import BySquare from "@/components/ui/BySquare";
import ByIcon from "@/components/ui/ByIcon";
import useFetch from "@/hooks/useFetch";
import ApiCrm from "@/api/crm";

type AttendanceRecord = {
  attendanceType: string;
  date: string;
  erpUserType: string;
  firstPicUrl: string;
  firstRecord: string;
  id: number;
  lastPicUrl: string;
  lastRecord: string;
  name: string;
  positionName: string;
  totalMin: number;
  workerTypeName: string;
  [property: string]: any;
};

const toHM = (totalMin: number) => {
  if (totalMin > 0) {
    // 计算小时数
    const hours = Math.floor(totalMin / 60);
    // 计算剩余的分钟数
    const minutes = totalMin % 60;

    let text = "";

    if (hours > 0) {
      text += hours.toString().padStart(2, "0") + "小时";
    }

    if (minutes > 0) {
      text += minutes.toString().padStart(2, "0") + "小时";
    }

    return text;
  }
};

const AttendanceRecordItem = ({ source }: { source: AttendanceRecord }) => {
  const { name, lastRecord, firstRecord, totalMin } = source;

  return (
    <Card className="m-3">
      <ByRow content="between">
        <View>
          <Text className="font-bold">{name}</Text>
          <Text className="text-sm text-third"></Text>
        </View>

        <Text>2025-03-21</Text>
      </ByRow>

      {totalMin > 0 && (
        <ByCell size="small" label="出勤时长">
          <ByText type="primary">{toHM(totalMin)}</ByText>
        </ByCell>
      )}

      <ByCell size="small" label="上班">
        {!!lastRecord && !firstRecord && (
          <ByText type="warning">上班未打卡</ByText>
        )}

        <Text>{firstRecord}</Text>
      </ByCell>
      <ByCell size="small" label="下班">
        {source.lastRecord}
      </ByCell>
    </Card>
  );
};

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const { data } = useFetch<any>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
  });

  const projectId = data?.intentCustomer.mkId;

  const { loading, list, nextPage } = useList<AttendanceRecord>(
    ApiMokan.attendanceRecord,
    { defaultParams: [{ intentCustomerId }] }
  );
  useReachBottom(nextPage);

  // 解绑设备
  const { loading: unbindLoading, run: runUnbind } = useFetch(
    ApiMokan.unBindDevice,
    {
      manual: true,
      showErrorToast: true,
      onSuccess() {
        Taro.showToast({ title: "解绑成功" });

        setTimeout(() => {
          Taro.reLaunch({
            url:
              `/packageProject/pages/detail/index?intentCustomerId=` +
              intentCustomerId,
          });
        }, 1500);
      },
    }
  );

  const toUnbind = async () => {
    if (unbindLoading) return;

    const { confirm } = await Taro.showModal({
      title: "解除摄像头绑定",
      content: "解绑后，需要重新绑定方可使用；其他工地可绑定本摄像头",
    });

    if (confirm) runUnbind({ intentCustomerId, projectId });
  };

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <FooterNav active={1} intentCustomerId={intentCustomerId} />
        }
      >
        <ListView loading={loading} isEmpty={list.length === 0}>
          {list.map((item) => (
            <AttendanceRecordItem source={item} key={item.id} />
          ))}
        </ListView>
      </Page>

      {projectId && (
        <BySquare
          className="bg-error fixed bottom-[200px] right-2 z-10"
          size={80}
          onClick={toUnbind}
        >
          <ByIcon name="Unbind" color="#fff" />
        </BySquare>
      )}
    </>
  );
};
